import 'dart:async';
import 'dart:convert';

import 'package:aihu_getx_app/app/modules/chat/models/user_view_export_req_vo.dart';
import 'package:aihu_getx_app/app/modules/chat/models/user_view_resp_vo.dart';
import 'package:aihu_getx_app/app/modules/chat/providers/chat_provider.dart';
import 'package:aihu_getx_app/app/modules/chat/utils/chat_constants.dart';
import 'package:aihu_getx_app/app/modules/commons/commons.dart';
import 'package:aihu_getx_app/providers/mqtt_provider.dart';
import 'package:aihu_getx_app/utils/constants.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';

class ChatController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final String title = "消息中心";
  final String appName = "";

  final count = 0.obs;
  MqttProvider? _mqqtProvider;
  final msgList = <String>[].obs;
  final userViewScrollController = ScrollController();
  final userViewList = <UserViewRespVO>[].obs;
  final loading = false.obs;
  late TabController tabController;
  final _typeList = UserViewListType.values;
  final tabList = <Tab>[].obs;
  final tabIndex = 0.obs;
  final searchForm = UserViewExportReqVO().obs;
  final loadMoreText = "已经到底了~".obs;
  late StreamSubscription<List<MqttReceivedMessage<MqttMessage>>>
      _listenSubscription;

  late StreamSubscription<Map<dynamic, dynamic>> _listEvenBusSubscription;

  Future onRefresh() {
    if (loading.isTrue) {
      return Future.value();
    }
    _onLoading();
    return Future.value();
  }

  void _onLoading() async {
    loading.value = true;
    try {
      var res = await ChatProvider.getUserViewList(searchForm.value);
      userViewList.value = res;
    } finally {
      loading.value = false;
    }
  }

  void tabChange(int index) {
    tabIndex.value = index;
    searchForm.update((val) {
      val!.listType = _typeList[index].type;
    });
    _onLoading();
  }

  @override
  void onInit() {
    super.onInit();
    tabList.value = _typeList.map((e) {
      return Tab(
        child: Text(
          e.description,
          style: Get.textTheme.titleSmall?.copyWith(color: Colors.white),
        ),
      );
    }).toList();
    tabController = TabController(length: tabList.length, vsync: this);
    _connect();
  }

  void _connect() async {
    var loginRes = Commons.getLoginResModel();
    if (loginRes == null) {
      return;
    }
    _mqqtProvider = MqttProvider.getInstance();
    _mqqtProvider!
        .connect(
      Constants.mqttBaseUrl,
      Constants.mqttPort,
      loginRes.accessToken!,
      Commons.getMqttUsername()!,
      loginRes.accessToken!,
    )
        .then((v) {
      if (v?.returnCode == MqttConnectReturnCode.connectionAccepted) {
        _mqqtProvider!.subscribeMessage(loginRes.chatTopic!);
        _startListen();
        _onLoading();
      }
    });
  }

  void sendMsg(String msg) {
    // if (_mqqtProvider?.isConnect() ?? false) {
    //   return;
    // }
    // _mqqtProvider!.sendMsg(msg);
  }

  @override
  void onReady() {
    super.onReady();
    //_onLoading();
  }

  @override
  void onClose() {
    super.onClose();
    _disconnect();
  }

  Widget buildProgressMoreIndicator() {
    return Padding(
      padding: const EdgeInsets.all(15.0),
      child: Center(
        child: Obx(
          () => Text(
            loadMoreText.value,
            style: Get.textTheme.bodyMedium,
          ),
        ),
      ),
    );
  }

  void increment() => count.value++;

//  监听消息的具体实现
  _onData(List<MqttReceivedMessage<MqttMessage>> data) {
    final MqttPublishMessage recMess = data[0].payload as MqttPublishMessage;
    final String topic = data[0].topic;
    final String pt = const Utf8Decoder().convert(recMess.payload.message);
    String desString = "topic is <$topic>, payload is <-- $pt -->";
    print("string =$desString");
    Map p = Map();
    p["topic"] = topic;
    p["type"] = "string";
    p["payload"] = pt;
  }

//  开启监听消息
  _startListen() {
    _listenSubscription = _mqqtProvider!.updates()!.listen(_onData);
  }

//  断开连接
  _disconnect() {
    _mqqtProvider?.disconnect();
  }
}
